//
//  JobListVC.m
//  MyProject
//
//  Created by 石小强 on 2018/3/21.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "JobListVC.h"
#import "JobListCell.h"
#import "AddJobIntensionVC.h"
#import "JobListFilterView.h"
#import "CompanyListFilterView.h"
#import "PositionModel.h"
#import "SelectCityViewController.h"
#import "CityModel.h"
#import "JobDetailVC.h"
#import "UITableView+Empty.h"

#define NormalFont [UIFont fontWithName:@"PingFangSC-Light" size:14]
#define SelectFont [UIFont fontWithName:@"PingFangSC-Regular" size:16]

@interface JobListVC ()

@property (nonatomic, strong) UIScrollView *menuV;
@property (nonatomic, assign) BOOL isScroll;
@property (nonatomic, strong) IntentionalModel *selectIntentional;
@property (nonatomic, strong) NSMutableArray *industryArray;
@property (nonatomic, strong) CityModel *selectCity;

@end

@implementation JobListVC {
    NSString *_region;
    
    NSString *_educational;
    NSString *_experience;
    NSString *_minSalary;
    NSString *_maxSalary;
    NSString *_jobNature;
    
    NSString *_financingScale;
    NSString *_personnelScale;
    NSString *_industryId;
    
    NSInteger _pageNo;
    BOOL _isRefreshNav;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNav];
    _isRefreshNav = NO;
    
    [self setupTableView];
    // 获取行业信息
    [self loadIndustriesData];
    
    [self.tableView.mj_header beginRefreshing];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SearchCityBlock:) name:@"searchcity" object:nil];
}

/** 加载导航栏 */
- (void)setupNav {
//    self.navigationItem.title = @"综合匹配";
    
    UIButton *addBtn = [[UIButton alloc] init];
    [addBtn setImage:[UIImage imageNamed:@"matching_ic_add"] forState:UIControlStateNormal];
    addBtn.mj_size = CGSizeMake(26, 26);
    [addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
    
//    UIScrollView *menuV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 88, 44)];
    UIScrollView *menuV = [[UIScrollView alloc] initWithFrame:CGRectMake(50, 0, kScreenWidth - 100, 44)];
    menuV.backgroundColor = [UIColor clearColor];
    self.menuV = menuV;
//    self.navigationItem.titleView = menuV;
    [self setupMenuView];
    [self.navigationController.navigationBar addSubview:menuV];
}

- (void)setupMenuView {
    for (UIView *cons in self.menuV.subviews) {
        [cons removeFromSuperview];
    }
    CGFloat contentX = 0;
    for (NSInteger i = 0; i < self.intentionalArray.count; i ++) {
        IntentionalModel *intentional = [self.intentionalArray objectAtIndex:i];
        NSString *titleStr = intentional.jobName;
        CGFloat titleW = 0;
        if (i == 0) {
            titleW = [Tool sizeWithText:titleStr font:SelectFont].width;
        } else {
            titleW = [Tool sizeWithText:titleStr font:NormalFont].width;
        }
        
        UIButton * button  = [[UIButton alloc] initWithFrame:CGRectMake(contentX, 0, titleW, 44)];
        button.backgroundColor = [UIColor clearColor];
        [self.menuV addSubview:button];
        [button setTitle:titleStr forState:UIControlStateNormal];
        [button setTitleColor:UIColorFromRGB(0x373B3C) forState:UIControlStateNormal];
        [button setTitleColor:UIColorFromRGB(0x373B3C) forState:UIControlStateSelected];
        if (i == 0) {
            button.titleLabel.font = SelectFont;
            
            self.selectIntentional = intentional;
        } else {
            button.titleLabel.font = NormalFont;
        }
        
        button.tag = i;
        [button addTarget:self action:@selector(menuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        contentX += titleW + 20;
    }
    
    self.menuV.contentSize = CGSizeMake(contentX - 20, 0);
    if (contentX - 20 > self.menuV.mj_w) {
        self.isScroll = YES;
    } else {
        self.isScroll = NO;
    }

}

- (void)menuBtnClick:(UIButton *)btn {
    NSInteger btnTag = btn.tag;
    self.selectIntentional = [self.intentionalArray objectAtIndex:btnTag];
    
    CGFloat contentX = 0;
    for (UIView *subV in self.menuV.subviews) {
        if ([subV isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)subV;
            
            NSString *titleStr = btn.titleLabel.text;
            CGFloat titleW = 0;
            if (btn.tag == btnTag) {
                titleW = [Tool sizeWithText:titleStr font:SelectFont].width;
                btn.titleLabel.font = SelectFont;
            } else {
                titleW = [Tool sizeWithText:titleStr font:NormalFont].width;
                btn.titleLabel.font = NormalFont;
            }
            btn.frame = CGRectMake(contentX, 0, titleW, 44);
            contentX += titleW + 20;
        }
    }
    self.menuV.contentSize = CGSizeMake(contentX - 20, 0);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.2 animations:^{
            CGFloat leftW = .0;
            CGFloat rightW = .0;
            
            for (NSInteger i = 0; i < btn.tag; i ++) {
                IntentionalModel *intentionM = [self.intentionalArray objectAtIndex:i];
                CGFloat w = [self widthForString:intentionM.jobName font:NormalFont];
                leftW = leftW + w + 20;
            }
            
            for (NSInteger i = (self.intentionalArray.count - 1); i > btn.tag ; i--) {
                IntentionalModel *intentionM = [self.intentionalArray objectAtIndex:i];
                CGFloat w = [self widthForString:intentionM.jobName font:NormalFont];
                rightW = rightW + w + 20;
            }
            
            IntentionalModel *selectIntentionM = [self.intentionalArray objectAtIndex:btn.tag];
            CGFloat selectBtnW = [self widthForString:selectIntentionM.jobName font:SelectFont];
            
            CGFloat offset = leftW + selectBtnW * 0.5;
            
            if (self.menuV.contentSize.width > self.menuV.frame.size.width) {
                if (offset > self.menuV.frame.size.width * 0.5) {
                    
                    if (offset - self.menuV.frame.size.width * 0.5 > self.menuV.contentSize.width - self.menuV.frame.size.width) {
                        [self.menuV setContentOffset:CGPointMake(self.menuV.contentSize.width - self.menuV.frame.size.width, 0) animated:YES];
                    } else {
                        [self.menuV setContentOffset:CGPointMake(offset - self.menuV.frame.size.width * 0.5, 0) animated:YES];
                    }
                } else {
                    [self.menuV setContentOffset:CGPointMake(0, 0) animated:YES];
                }
            }
        }];
    });
    
    if (contentX - 20 > self.menuV.mj_w) {
        self.isScroll = YES;
    } else {
        self.isScroll = NO;
    }
    
    _region = @"";
    _educational = @"";
    _experience = @"";
    _minSalary = @"";
    _maxSalary = @"";
    _financingScale = @"";
    _personnelScale = @"";
    _industryId = @"";
    _jobNature = @"";
    [self.regionBtn setTitle:@"区域" forState:UIControlStateNormal];
    [self.regionBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:6.0];
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)addBtnClick {
    if (self.intentionalArray.count >= 3) {
        [CommonUtils showToast:@"最多添加三个意向职位"];
        return;
    } else if (self.intentionalArray.count < 3) {
        AddJobIntensionVC *add = [[AddJobIntensionVC alloc] init];
        add.index = 0;
        add.addBlock = ^{
            _isRefreshNav = YES;
            /** 获取意向职位列表 */
            [self loadIntentionPositionData];
        };
        [self.navigationController pushViewController:add animated:YES];
    } else {
        
    }
}

- (void)setupTableView {
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([JobListCell class]) bundle:nil] forCellReuseIdentifier:@"JobListCell"];
    
    self.tableHeaderView.frame = CGRectMake(0, 0, kScreenWidth, 40);
    self.tableView.tableHeaderView = self.tableHeaderView;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageNo = 1;
        [self.tableView haveDataRemoveEmptyUI];
        [self loadListData];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _pageNo += 1;
        [self loadListData];
    }];
    
    [self.regionBtn setTitle:@"区域" forState:UIControlStateNormal];
    [self.regionBtn setImage:[UIImage imageNamed:@"ic_more_jobList"] forState:UIControlStateNormal];
    [self.regionBtn setTitleColor:UIColorFromRGB(0x686563) forState:UIControlStateNormal];
    [self.regionBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:6.0];
    
    [self.positionBtn setTitle:@"职位筛选" forState:UIControlStateNormal];
    [self.positionBtn setTitle:@"职位筛选" forState:UIControlStateSelected];
    [self.positionBtn setImage:[UIImage imageNamed:@"ic_more_jobList"] forState:UIControlStateNormal];
    [self.positionBtn setImage:[UIImage imageNamed:@"ic_more_up_jobList"] forState:UIControlStateSelected];
    [self.positionBtn setTitleColor:UIColorFromRGB(0x686563) forState:UIControlStateNormal];
    [self.positionBtn setTitleColor:UIColorFromRGB(0x43C4D1) forState:UIControlStateSelected];
    [self.positionBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:6.0];
    
    [self.companyBtn setTitle:@"企业筛选" forState:UIControlStateNormal];
    [self.companyBtn setTitle:@"企业筛选" forState:UIControlStateSelected];
    [self.companyBtn setImage:[UIImage imageNamed:@"ic_more_jobList"] forState:UIControlStateNormal];
    [self.companyBtn setImage:[UIImage imageNamed:@"ic_more_up_jobList"] forState:UIControlStateSelected];
    [self.companyBtn setTitleColor:UIColorFromRGB(0x686563) forState:UIControlStateNormal];
    [self.companyBtn setTitleColor:UIColorFromRGB(0x43C4D1) forState:UIControlStateSelected];
    [self.companyBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:6.0];
}

/** 查询意向职位列表 */
- (void)loadIntentionPositionData {
    WS(weakSelf)
    [SendRequest getIntentionalPositionWithResult:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"查询意向职位列表 = %@", [result objectForKey:@"data"]);
            NSArray *datas = [IntentionalModel mj_objectArrayWithKeyValuesArray:[result objectForKey:@"data"]];
            [weakSelf.intentionalArray removeAllObjects];
            [weakSelf.intentionalArray addObjectsFromArray:datas];
            
            if (_isRefreshNav) {
                [weakSelf setupMenuView];
                
                _region = @"";
                _educational = @"";
                _experience = @"";
                _minSalary = @"";
                _maxSalary = @"";
                _financingScale = @"";
                _personnelScale = @"";
                _industryId = @"";
                _jobNature = @"";
                [self.regionBtn setTitle:@"区域" forState:UIControlStateNormal];
                [self.regionBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:6.0];
                
                [weakSelf.tableView.mj_header beginRefreshing];
            }
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

/** 获取行业信息 */
- (void)loadIndustriesData {
    WS(weakSelf)
    [self showProgressWithView:self.view animated:YES];
    [SendRequest getIndustriesWithResult:^(NSDictionary *result, NSError *error) {
        [weakSelf hideProgress:self.view animated:YES];
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1)
        {
            SaintiLog(@"获取行业信息--返回值 = %@", result);
            [weakSelf.industryArray removeAllObjects];
            NSArray *datas = [IndustryModel mj_objectArrayWithKeyValuesArray:[result objectForKey:@"data"]];
            [weakSelf.industryArray addObjectsFromArray:datas];
        }else{
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
        
    }];
    
}

/** 加载页面列表数据 */
- (void)loadListData {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"pageNo"] = [NSString stringWithFormat:@"%zd", _pageNo];
    params[@"pageSize"] = kNumOfPageSize;
    params[@"jobId"] = self.selectIntentional.jobId;
    if (_region && _region.length > 0) {
        params[@"region"] = _region;
    }
    if (_educational && _educational.length > 0) {
        params[@"requiredEducational"] = _educational;
    }
    if (_experience && _experience.length > 0) {
        params[@"requiredExperience"] = _experience;
    }
    if (_minSalary && _minSalary.length > 0) {
        params[@"minSalary"] = _minSalary;
    }
    if (_maxSalary && _maxSalary.length > 0) {
        params[@"maxSalary"] = _maxSalary;
    }
    if (_jobNature && _jobNature.length > 0) {
        params[@"jobNature"] = _jobNature;
    }
    if (_financingScale && _financingScale.length > 0) {
        params[@"financingScale"] = _financingScale;
    }
    if (_personnelScale && _personnelScale.length > 0) {
        params[@"personnelScale"] = _personnelScale;
    }
    if (_industryId && _industryId.length > 0) {
        params[@"industryId"] = _industryId;
    }
    WS(weakSelf)
    [SendRequest getPostionListByParam:params result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"查询职位(多条件筛选)列表 = %@", [result objectForKey:@"data"]);
            
            NSArray *datas = [PositionModel mj_objectArrayWithKeyValuesArray:[[result objectForKey:@"data"] objectForKey:@"list"]];
            if (_pageNo == 1) {
                [weakSelf.positionArray removeAllObjects];
                [weakSelf.positionArray addObjectsFromArray:datas];
                [weakSelf.tableView.mj_header endRefreshing];
                
                if (datas.count == 0) {
                    [weakSelf.tableView noDataAddEmptyUIWithImageName:@"pic_emptystate_two" andEmptyText:@"暂无相关数据" andTopDistance:130];
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [weakSelf.tableView haveDataRemoveEmptyUI];
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            } else {
                [weakSelf.positionArray addObjectsFromArray:datas];
                if (datas.count < kNumOfPageIntSize) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [weakSelf.tableView.mj_footer endRefreshing];
                }
            }
            
            [weakSelf.tableView reloadData];
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

- (void)SearchCityBlock:(NSNotification *)notification {
    // 得到传递的参数
    NSDictionary *dict = [notification userInfo];
    // 重新选择收货地址后，走此条件
    CityModel *city = [dict objectForKey:@"city"];
    
    self.selectCity = city;
    _region = city.regionId;
    [self.regionBtn setTitle:city.regionName forState:UIControlStateNormal];
    CGFloat space = 6.0;
    [self.regionBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:space];
    self.regionBtn.adjustsImageWhenHighlighted = NO;
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - 筛选按钮点击事件

- (IBAction)filterBtnClick:(id)sender {
    if (sender == self.regionBtn) {
        SelectCityViewController *scVC = [[SelectCityViewController alloc] init];
        scVC.cityBlock = ^(CityModel *city) {
            self.selectCity = city;
            _region = city.regionId;
            [self.regionBtn setTitle:city.regionName forState:UIControlStateNormal];
            CGFloat space = 6.0;
            [self.regionBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:space];
            self.regionBtn.adjustsImageWhenHighlighted = NO;
            [self.tableView.mj_header beginRefreshing];
        };
//        [self.navigationController pushViewController:scVC animated:YES];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:scVC];
        [self presentViewController:nav animated:YES completion:nil];
        
    } else if (sender == self.companyBtn) {
        CompanyListFilterView *filterV = [[CompanyListFilterView alloc] init];
        filterV.industryArray = self.industryArray;
        self.companyBtn.selected = YES;

        filterV.dismissBlock = ^(NSString *financingScale, NSString *personnelScale, NSString *industryId) {
            _financingScale = financingScale;
            _personnelScale = financingScale;
            _industryId = industryId;
            
            self.companyBtn.selected = NO;
            [self.tableView.mj_header beginRefreshing];
        };
        filterV.justDismissBlock = ^{
            self.companyBtn.selected = NO;
        };
        [filterV show];
    } else if (sender == self.positionBtn) {
        JobListFilterView *filterV = [[JobListFilterView alloc] init];
        self.positionBtn.selected = YES;

        filterV.dismissBlock = ^(NSString *educational, NSString *experience, NSString *minSalary, NSString *maxSalary, NSString *jobNature) {
            _educational = educational;
            _experience = experience;
            _minSalary = minSalary;
            _maxSalary = maxSalary;
            _jobNature = jobNature;
            
            self.positionBtn.selected = NO;
            [self.tableView.mj_header beginRefreshing];
        };
        filterV.justDismissBlock = ^{
            self.positionBtn.selected = NO;
        };
        [filterV show];
    }
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.positionArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JobListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JobListCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = [self.positionArray objectAtIndex:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    JobDetailVC *vc = [[JobDetailVC alloc] init];
    
    PositionModel *position = [self.positionArray objectAtIndex:indexPath.row];
    vc.positionId = position.positionId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSMutableArray *)intentionalArray {
    if (!_intentionalArray) {
        _intentionalArray = [[NSMutableArray alloc] init];
    }
    return _intentionalArray;
}

- (NSMutableArray *)positionArray {
    if (!_positionArray) {
        _positionArray = [[NSMutableArray alloc] init];
    }
    return _positionArray;
}

- (float) widthForString:(NSString *)value font:(UIFont *)font
{
    NSDictionary *attributes = @{NSFontAttributeName:font};
    CGRect rect =[value boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil];
    return rect.size.width;
}

- (NSMutableArray *)industryArray {
    if (!_industryArray) {
        _industryArray = [[NSMutableArray alloc] init];
    }
    return _industryArray;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.menuV.hidden = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.menuV.hidden = NO;
}

- (void)doBack:(id)sender {
    [self.menuV removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
